//
//  DrugsAssembly.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/4.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON


/// 每个药方的内容部分组件
class DrugsAssembly: UIView {
    /// 标题
    let title = UILabel()
    // 删除按钮
    let deleteBtn = UIButton()
    // 容器
    let headView = UIView()
    /// 查看更多
    let moreBtn = UIButton()
    
    /// 这个组件高度
    var drugsH: CGFloat = 0.0
    
    var drugsBlock: ((_ drugsViewBtn:UIButton) -> (Void))?
    
    init(_ target: Any?, json: JSON) {
        super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 308))
        self.backgroundColor = UIColor.clear
        setupViews(view: self , json: json)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupViews(view: UIView , json: JSON) {
        view.addSubview(headView)
        view.addSubview(moreBtn)
        view.addSubview(title)
        view.addSubview(deleteBtn)
        
        let w = UIScreen.main.bounds.size.width - 32
        
        headView.topAlign(view: view, predicate: "0")
        headView.leadingAlign(view: view)
        headView.trailingAlign(view: view)
        headView.heightConstrain(predicate: "40")
        headView.addSubview(title)
        headView.addSubview(deleteBtn)
        headView.addLayer(isAddLayer: (false, false, false, true), color: configure.shareConfigure.HMColor1, crude: 2, layout: (w: w, h: 40))
        
        
        title.topAlign(view: headView, predicate: "0")
        title.leadingAlign(view: headView, predicate: "0")
        title.heightConstrain(predicate: "40")
        title.text =  json["nameType"].stringValue  //"王医生 (健康咨询):"
        
        deleteBtn.topAlign(view: headView, predicate: "0")
        deleteBtn.trailingAlign(view: headView, predicate: "0")
        deleteBtn.setImage(UIImage.init(named: "trash"), for: .normal)
        deleteBtn.setTitleColor(UIColor.black, for: .normal)
        deleteBtn.heightConstrain(predicate: "40")
        deleteBtn.addTarget(self, action: #selector(deleteBtnClick), for: UIControlEvents.touchUpInside)
        

        
        // 药品部分
        let dev: JSON = json["drugsAry"] //[["drugsName":"药名", "period": "疗程"]]  //["drugsName":"药名", "period": "疗程"],["drugsName":"药名", "period": "疗程"],["drugsName":"药名", "period": "疗程"],["drugsName":"药名", "period": "疗程"]]
        
        
        let a = DrugsView()
        view.addSubview(a)
        let aItem = a.setViews(json: dev)
        a.topVertically(view: headView, predicate: "0")
        a.leadingAlign(view: view, predicate: "0")
        a.trailingAlign(view: view, predicate: "0")
        a.backgroundColor = UIColor.clear
        a.heightConstrain(predicate: "\(aItem.1)")
        
        // 更多
        moreBtn.topVertically(view: a, predicate: "0")
        moreBtn.trailingAlign(view: view, predicate: "0")
        moreBtn.heightConstrain(predicate: "40")
        moreBtn.setTitle(json["moreBtnName"].stringValue, for: .normal)
        moreBtn.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        moreBtn.addTarget(self, action: #selector(moreBtnClick), for: UIControlEvents.touchUpInside)
        
    
        // 建议部分
        let b = AdviceLife()
         view.addSubview(b)
        let dev1: JSON = json["adviceLife"]
        let bItem = b.setViews(json: dev1)
        b.topVertically(view: moreBtn, predicate: "0")
        b.leadingAlign(view: view)
        b.trailingAlign(view: view, predicate: "0")
        b.heightConstrain(predicate: "\(bItem.1)")
        
        // 按钮
        let btn = BtnRLView()
        view.addSubview(btn)
        let btnItem = btn.setViews(json: ["L": "一键购买", "R": json["btnItemName"].stringValue], self, lSelector: #selector(buyBtnClick), rSelector: #selector(addBtnClick))
        btn.topVertically(view: b)
        btn.leadingAlign(view: view)
        btn.trailingAlign(view: view)
        btn.heightConstrain(predicate: "\(btnItem.1)")
        
        self.drugsH = 40.0 + aItem.1 + 40.0 + bItem.1 + 40.0 + 16.0
    }
    
    @objc func deleteBtnClick(sender: UIButton) {
         print("-----删除", sender)
        self.drugsBlock?(sender)
    }
    @objc func moreBtnClick(sender: UIButton) {
        print("-----查看更多", sender)
        self.drugsBlock?(sender)
    }
    
    @objc func buyBtnClick(sender: UIButton) {
        print("-----一键购买", sender)
        self.drugsBlock?(sender)
    }
    @objc func addBtnClick(sender: UIButton) {
        print("-----添加提醒", sender)
        self.drugsBlock?(sender)
    }
}


/// 药品组件（缩略）
class DrugsView : UIView {
    
    static let shareDrugsView:  DrugsView  = {
        let share = DrugsView()
        return share
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setViews(json: JSON) -> (CGFloat, CGFloat) {
        let w = UIScreen.main.bounds.size.width   //- 16
        var itemH: CGFloat = 0.0
        var topH: CGFloat = 0.0
        let height:  CGFloat = 40.0
        var interval: CGFloat = 0.0
        
        if json != JSON.null {
            itemH = height * CGFloat(json.count) //+  CGFloat(json.count * 2)
            for (i,item) in json {
                    let l1 = UILabel()
                    let l2 = UILabel()
                    self.addSubview(l1)
                    self.addSubview(l2)

                
                    topH = height * CGFloat(Int(i)!)
                    interval = 0
                    l1.topAlign(view: self, predicate: "\(topH + interval)")
                    l1.leadingAlign(view: self)
                    l1.heightConstrain(predicate: "\(height)")
                    l1.width(view: self, predicate: "*0.5")
                    l1.text = item["medicineName"].stringValue   //drugsName -药名
                    l1.addLayer(isAddLayer: (false, false, false, true), color: configure.shareConfigure.HMColor3, crude: 1, layout: (w: w/2, h: height))
                    l1.textAlignment = .center
                    
                    l2.topAlign(view: self, predicate: "\(topH + interval)")
                    l2.trailingAlign(view: self)
                    l2.heightConstrain(predicate: "\(height)")
                    l2.width(view: self, predicate: "*0.5")
                    l2.text = item["treatment"].stringValue  // period
                    l2.addLayer(isAddLayer: (true, false, false, true), color: configure.shareConfigure.HMColor3, crude: 1, layout: (w: w/2 - 8, h: height))
                    l2.textAlignment = .center
                
                
                if i != "0" {
                    l1.textColor = configure.shareConfigure.HMColor4
                    l2.textColor = configure.shareConfigure.HMColor4
                }
            }
        }

        return (top: topH, height:itemH )
    }

    
}


/// 生活建议组件
class AdviceLife : UIView {
    
//    let life = UILabel()
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setViews(json: JSON) -> (CGFloat, CGFloat) {
        var itemH: CGFloat = 0.0
        var topH: CGFloat = 40.0
        let height:  CGFloat = 30.0
        let titleLable = UILabel()
        self.addSubview(titleLable)
        
        titleLable.topAlign(view: self, predicate: "0")
        titleLable.text =  json["title"].stringValue
        titleLable.font =  configure.shareConfigure.HMSize_20
        titleLable.leadingAlign(view: self, predicate: "0")
        titleLable.trailingAlign(view: self, predicate: "0")
        titleLable.heightConstrain(predicate: "40")
        titleLable.backgroundColor = .clear
        
        
        if json != JSON.null {
            let ary = json["ary"].arrayValue
            var tH: CGFloat = 0.0
            var i = 0
           // itemH = height * CGFloat(ary.count) +  CGFloat(ary.count) + 40
            for item in ary {
                let l1 = UILabel()
                l1.numberOfLines = 0
                l1.lineBreakMode = NSLineBreakMode.byWordWrapping
                l1.font = UIFont.systemFont(ofSize: 15)
                let itemSize =  String.getTextRectSize(text: item.stringValue as NSString, font: 15, size: CGSize.init(width: configure.shareConfigure.screenWidth - 18.0, height: 300.0))
                self.addSubview(l1)
                topH = CGFloat(tH)  //(height) * CGFloat(i)
                l1.topVertically(view: titleLable, predicate: "\(topH)")
                l1.leadingAlign(view: self, predicate: "10")
                l1.trailingAlign(view: self)
                l1.heightConstrain(predicate: "\(itemSize.height)")
                tH +=  itemSize.height
//                l1.heightConstrain(predicate: "\(height)")
//                l1.text = "\(i + 1).\(item)"
                l1.text = "\(item)"
                l1.textAlignment = .left
                i += 1
            }
            itemH = tH + CGFloat(ary.count) + 40
        }
        
        return (top: topH, height:itemH)
    }

}

/// 按钮组件 (药品建议 + 提问部分)
class BtnRLView: UIView {
    var topH: CGFloat = 0.0
    var itemH: CGFloat = 0.0
    /// self view height - 40
    private let height:  CGFloat = 40.0
    let butL = UIButton()
    let butR = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setViews(json: JSON,  _ target: Any?, lSelector L: Selector, rSelector R: Selector) -> (CGFloat, CGFloat) {
        self.addSubview(butL)
        self.addSubview(butR)
        // 按钮
        butL.topAlign(view: self, predicate: "0")
        butL.heightConstrain(predicate: "\(height)")
        butL.leadingAlign(view: self, predicate: "0")
        butL.widthConstrain(predicate: "100")
        
        butL.setTitle(json["L"].stringValue, for: .normal)
        
        butL.setTitleColor(.black, for: .normal)
        butL.backgroundColor = .white
        butL.layer.borderWidth = 1
        butL.layer.borderColor = UIColor.gray.cgColor
        butL.layer.cornerRadius = 6
        butL.addTarget(target, action: L, for: UIControlEvents.touchUpInside)
        butL.isHidden = true // 隐藏购买按钮
        
        
        butR.topAlign(view: self, predicate: "0")
        butR.heightConstrain(predicate: "\(height)")
        butR.trailingAlign(view: self, predicate: "0") // (view: view)
        butR.widthConstrain(predicate: "100")
        butR.setTitle(json["R"].stringValue, for: .normal)
        butR.setTitleColor(.white, for: .normal)
        butR.backgroundColor = configure.shareConfigure.HMColor1
        butR.layer.cornerRadius = 6
        butR.addTarget(target, action: R, for: UIControlEvents.touchUpInside)
        
       itemH = height
       return (top: topH, height:itemH)
    }
}
